package com.yifushidai.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yifushidai.mapper.TokenEntityMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 极光推送  app将用户id设为别名
 */
public class JPushUtils {
    private static final Logger logger = LoggerFactory.getLogger(JPushUtils.class);

    public static final int LOG_LOCK_OPEN_NOTIFICATION_TYPE = 0;//开门记录通知类型
    public static final int LOG_POWER_STATUS_NOTIFICATION_TYPE = 1;//控电记录通知类型
    public static final int OTHER_NOTIFICATION_TYPE = 2;//其他通知类型

    private static JPushClient shisuClient = new JPushClient(
            "fc2f0aafb329efc0db8df65f",
            "0bf3557826dc2ae7066b962b",
            null,
            ClientConfig.getInstance());
    private static JPushClient apartmentClient = new JPushClient(
            "2c13566b559c2c4357fce1cf",
            "0ece678c3fcc98b9d52dd2f2",
            null,
            ClientConfig.getInstance());

    public static void main(String[] args) throws Exception {
        testNotification();
    }

    /**
     * 极光通知 测试
     */
    private static void testNotification() throws Exception {
        Set<String> mobileSet = new LinkedHashSet<>();
        mobileSet.add("17711351006");
        jNotification(mobileSet, "重要通知：因业务升级工作，系统将于4月26日（星期五）下午15:30~16:00进行升级维护，之后正常开放。期间用户无法进行登录、查询等业务。望周知！对于给您带来的不便，敬请谅解！", "拾宿通知", JPushUtils.OTHER_NOTIFICATION_TYPE);
    }

    /**
     * 极光透传 测试
     */
    public static void testMessage() throws Exception {
        String alias = "17711351006";//声明别名
        JSONObject msgContent = new JSONObject();
        msgContent.put("key1", "中文key1");
        msgContent.put("key2", 222.02);
        msgContent.put("key3", Boolean.TRUE);
        PushResult result = jMessage(alias, msgContent);
        System.out.println(result.isResultOK());
    }

    public static void shisuNotification(TokenEntityMapper tokenEntityMapper, Set<String> mobileSet, String alert, int typeNum) {
        Set<String> alias = new LinkedHashSet<>();
        for (String mobile : mobileSet) {
            if (StringUtils.isNotBlank(mobile)) {
//                alias.add(tokenEntityMapper.selectByPrimaryKey(mobile).getToken());
                alias.add(mobile);
            }
        }
        jNotification(alias, alert, "拾宿通知", typeNum);
    }

    /**
     * 生成极光通知对象PushPayload（采用java SDK）
     *
     * @param alias   别名 可以使用户的id 编号
     * @param alert   通知显示的消息体
     * @param title   通知显示的标题
     * @param typeNum 自定义消息类型
     * @return PushPayload
     */
    private static PushResult jNotification(Set<String> alias, String alert, String title, int typeNum) {
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle(title)
                                .setAlert(alert)
                                .addExtra("type", typeNum)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setSound("default")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）（不设置默认 生产环境）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
        logger.info(">>> 拾宿通知：{} 参数：{}", alias, alert);
        return sendPush(shisuClient, payload);
    }

    /**
     * 生成极光透传对象PushPayload（采用java SDK）
     *
     * @param alias      别名 可以使用户的id 编号
     * @param msgContent 通知显示的消息体
     * @return PushPayload
     */
    private static PushResult jMessage(String alias, JSONObject msgContent) {
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setMessage(Message.newBuilder()
                        .setTitle("拾宿透传")
                        .setMsgContent(JSON.toJSONString(msgContent))
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）（不设置默认 生产环境）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
        logger.info(">>> 拾宿透传：{} 参数：{}", alias, msgContent);
        return sendPush(shisuClient, payload);
    }

    private static PushResult sendPush(JPushClient jPushClient, PushPayload payload) {
        try {
            return jPushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
//            logger.warn("HTTP Status: " + e.getStatus());
//            logger.warn("Error Code: " + e.getErrorCode());
//            logger.warn("Error Message: " + e.getErrorMessage());
//            logger.warn("Msg ID: " + e.getMsgId());
            return null;
        }
    }
}